#encoding=utf8
'''
Created on Aug 10, 2015

@author: jingyang <jingyang@smalltreemedia.com>
'''
from django.db import models
from core.fields import CustomTextField
from core.widgets import CustomTextarea
from django.utils import timezone


QA_STATUS = (
    ('P', 'Pending'),
    ('I', 'In Progress'),
    ('D', 'Cleared'),
    ('O', 'On Hold'),
    ('X', 'Cancelled')
)


class DevQAInfoManager(models.Manager):
    def get_latest_num(self):
        current_year = timezone.now().year
        current_month = timezone.now().month
        current_day = timezone.now().day
        latest = self.filter(
            create_time__year=current_year,
            create_time__month=current_month,
            create_time__day=current_day).order_by('-request_id')[:1]
        return int(latest[0].request_id[-2:]) + 1 if latest else 1


class DevQAInfo(models.Model):
    # basic info
    request_id = models.CharField('Dev QA Request ID', max_length=20,
        unique=True)
    app = models.ForeignKey('app_info.App', verbose_name='App',
        limit_choices_to={'status': 'V'})
    version = models.CharField('Version Code', max_length=10)
    code_dir = CustomTextField('Code Directory', widget=CustomTextarea)
    editor = models.CharField('Requested By', max_length=50)
    create_time = models.DateTimeField('Requested At', auto_now_add=True)
    # progress
    status = models.CharField('Dev QA Status', max_length=1, default='P',
        choices=QA_STATUS, null=True, blank=True)
    tester = models.CharField('Tester', max_length=200, null=True, blank=True)
    bug_addr = models.URLField('Bug Tracker Project Address', null=True,
        blank=True)
    real_clear_at = models.DateField('Actual Dev QA Clear Date', null=True,
        blank=True)
    bugs_count = models.IntegerField('No. of Bugs', null=True, blank=True)
    time_spent = models.IntegerField('Time Spent', null=True, blank=True)
    days_pending = models.FloatField('Days Pending Dev QA', null=True,
        blank=True)
    days_qa = models.FloatField('Days in Dev QA', null=True, blank=True)
    days_total = models.FloatField('Total Days in Dev QA', null=True,
        blank=True)

    objects = DevQAInfoManager()

    def get_app_version(self):
        vs = self.app.appversion_set.filter(code=self.version).exclude(status='C')[:1]
        return None if not vs else vs[0]

    def get_last_pending_time(self):
        last_pending = self.devqastatusrecord_set.filter(status_after='P')[:1]
        return last_pending[0].timestamp if last_pending else self.create_time

    def get_last_progress_time(self):
        last_progress = self.devqastatusrecord_set.filter(status_after='I')[:1]
        return last_progress[0].timestamp if last_progress else None

    def __unicode__(self):
        return self.request_id

    class Meta:
        verbose_name = 'Dev QA Request'
        verbose_name_plural = 'Dev QA Requests'


class DevQAStatusRecord(models.Model):
    dev_qa_info = models.ForeignKey(DevQAInfo, verbose_name='Dev QA Request')
    editor = models.CharField('Editor', max_length=50)
    status_before = models.CharField('Status (Before)', max_length=1,
        choices=QA_STATUS)
    status_after = models.CharField('Status (After)', max_length=1,
        choices=QA_STATUS)
    timestamp = models.DateTimeField('Timestamp', auto_now_add=True)

    class Meta:
        verbose_name = 'Dev QA Status Record'
        verbose_name_plural = 'Dev QA Status Record'


class DevQANote(models.Model):
    dev_qa_info = models.ForeignKey(DevQAInfo, verbose_name='Dev QA Request')
    content = CustomTextField('Notes', widget=CustomTextarea)
    editor = models.CharField('Editor', max_length=50)
    timestamp = models.DateTimeField('Timestamp', auto_now_add=True)

    def __unicode__(self):
        return 'Dev QA Notes'

    class Meta:
        verbose_name = 'Dev QA Notes'
        verbose_name_plural = 'Dev QA Notes'


class ReleaseQAInfoManager(models.Manager):
    def get_latest_num(self):
        current_year = timezone.now().year
        current_month = timezone.now().month
        current_day = timezone.now().day
        latest = self.filter(
            create_time__year=current_year,
            create_time__month=current_month,
            create_time__day=current_day).order_by('-request_id')[:1]
        return int(latest[0].request_id[-2:]) + 1 if latest else 1

    def create(self, **kwargs):
        now = timezone.now()
        kwargs.update({'request_id': 'RQA2-%s%02i%02i%02i' % (now.year,
            now.month, now.day, self.get_latest_num())})
        return models.Manager.create(self, **kwargs)


class ReleaseQAInfo(models.Model):
    # basic info
    dev_qa = models.ForeignKey(DevQAInfo, verbose_name='Dev QA Request')
    request_id = models.CharField('Release QA Request ID', max_length=20,
        unique=True)
    sub_info = models.ForeignKey('sub_info.SubInfo',
        verbose_name='Submission Request')
    create_time = models.DateTimeField('Requested At', auto_now_add=True)
    editor = models.CharField('Requested By', max_length=50)
    # progress
    status = models.CharField('Release QA Status', max_length=1, default='P',
        choices=QA_STATUS)
    tester = models.CharField('Tester', max_length=200, null=True, blank=True)
    real_clear_at = models.DateField('Release QA Clear Date', null=True,
        blank=True)
    bugs_count = models.IntegerField('No. of Bugs', default=0)
    time_spent = models.IntegerField('Time Spent', default=0)
    # check list
    ad_sdk = models.BooleanField('Ad SDK', default=False)
    analytics_sdk = models.BooleanField('Analytics SDK', default=False)
    newsblast_sdk = models.BooleanField('News Blast SDK', default=False)
    studio_sdk = models.NullBooleanField('Studio SDK', default=None)
    about_page = models.NullBooleanField('About Page', default=None)
    version_checker = models.NullBooleanField('Version Checker', default=None)
    checked_by = models.CharField('Checked By', max_length=50, null=True,
        blank=True)
    other = CustomTextField('Other', widget=CustomTextarea, null=True,
        blank=True)

    objects = ReleaseQAInfoManager()

    def __unicode__(self):
        return self.request_id

    class Meta:
        verbose_name = 'Release QA Request'
        verbose_name_plural = 'Release QA Requests'


class ReleaseQAStatusRecord(models.Model):
    release_qa_info = models.ForeignKey(ReleaseQAInfo,
        verbose_name='Release QA Request')
    editor = models.CharField('Editor', max_length=50)
    status_before = models.CharField('Status (Before)', max_length=1,
        choices=QA_STATUS)
    status_after = models.CharField('Status (After)', max_length=1,
        choices=QA_STATUS)
    timestamp = models.DateTimeField('Timestamp', auto_now_add=True)

    class Meta:
        verbose_name = 'Release QA Status Record'
        verbose_name_plural = 'Release QA Status Record'


class ReleaseQANote(models.Model):
    release_qa_info = models.ForeignKey(ReleaseQAInfo,
        verbose_name='Release QA Request')
    content = CustomTextField('Notes', widget=CustomTextarea)
    editor = models.CharField('Editor', max_length=50)
    timestamp = models.DateTimeField('Timestamp', auto_now_add=True)

    def __unicode__(self):
        return 'Release QA Notes'

    class Meta:
        verbose_name = 'Release QA Notes'
        verbose_name_plural = 'Release QA Notes'
